package cn.dankal.flyaudio.store;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jyj.recruitment.wxapi.PayUtils;
import com.jyj.recruitment.wxapi.WxConstants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import androidx.lifecycle.Observer;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.ShopUserServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.ProductEntity;
import cn.dankal.basiclib.pojo.StoreHomeEntity;
import cn.dankal.basiclib.pojo.WexinPayResult;
import cn.dankal.basiclib.pojo.req.AddShopCarReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.TabMainActivity;
import cn.dankal.flyaudio.adapter.StoreProductAdapter;
import cn.dankal.flyaudio.configs.PayConfigs;
import cn.dankal.flyaudio.friend.pickimage.StringUtil;
import cn.dankal.flyaudio.personal.MyOrderDetailActivity;
import cn.dankal.flyaudio.pop.AddShopCarPop;
import cn.dankal.flyaudio.pop.PayMethodPop;
import razerdp.basepopup.BasePopupWindow;

import static com.jyj.recruitment.wxapi.WxConstants.PAY_FAILED;
import static com.jyj.recruitment.wxapi.WxConstants.PAY_SUCCESS;

public class PayResultActivity extends BaseActivity implements View.OnClickListener {
    private String payUuid;
    private boolean isPaySuccess = false;

    private ImageView payResultImg;

    private TextView payResultTitle;

    private TextView payResultHandle1;

    private TextView payResultHandle2;

    private RecyclerView hotProductView;

    private StoreProductAdapter hotProductAdapter;
    private String productId;

    private PayReceive receive = new PayReceive();
    /**
     * 标识页面类型，为空代表支付，不为空代表评价
     */
    private String type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay_result;
    }

    @Override
    protected void initComponents() {
        type = getIntent().getStringExtra("type");
        productId = getIntent().getStringExtra("uuid");
        if (StringUtil.isEmpty(type)) {
            addSingleTitleBar("支付结果");
        } else {
            addSingleTitleBar("评价成功");
        }

        payResultImg = findViewById(R.id.iv_pay_result_img);
        payResultTitle = findViewById(R.id.iv_pay_result_title);
        payResultHandle1 = findViewById(R.id.tv_handle_1);
        hotProductView = findViewById(R.id.recyclerview);
        payResultHandle2 = findViewById(R.id.tv_handle_2);
        payResultHandle1.setOnClickListener(this);
        payResultHandle2.setOnClickListener(this);
        hotProductAdapter = new StoreProductAdapter();
        hotProductView.setLayoutManager(new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        hotProductAdapter.setType("2");
        hotProductView.setAdapter(hotProductAdapter);
        LiveEventBus.get("StoreProductJoin2", ProductEntity.class)
                .observe(this, new Observer<ProductEntity>() {
                    @Override
                    public void onChanged(ProductEntity s) {
                        //加入购物车
                        searchSku(s.getUuid());
                    }
                });
        payUuid = getIntent().getStringExtra("orderUuid");
        if (StringUtil.isEmpty(type)) {
            isPaySuccess = getIntent().getBooleanExtra("isPaySuccess", false);
            if (isPaySuccess) {
                payResultImg.setImageResource(R.mipmap.undraw_confirmation_2uy0);
                payResultTitle.setText("支付成功");
                payResultHandle2.setText("查看订单");
                payResultHandle1.setText("返回首页");
            } else {
                payResultImg.setImageResource(R.mipmap.undraw_confirmation_zhifushibai);
                payResultTitle.setText("支付失败");
                payResultHandle2.setText("查看订单");
                payResultHandle1.setText("重新付款");
                payResultHandle1.setTextColor(Color.parseColor("#0084b0"));
            }
        } else {
            payResultImg.setImageResource(R.mipmap.undraw_confirmation_2uy0);
            payResultTitle.setText("评价成功");
            payResultHandle1.setText("返回首页");
            payResultHandle2.setText("查看评价");
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PAY_FAILED);
        initData();
        intentFilter.addAction(PAY_SUCCESS);
        LocalBroadcastManager.getInstance(this).registerReceiver(receive, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receive);
    }

    private void initData() {
        ShopUserServiceFactory.storeHome()
                .subscribe(new AbstractSubscriber<BaseResponse<StoreHomeEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<StoreHomeEntity> storeHomeEntityBaseResponse) {
                        hotProductAdapter.addDatas(storeHomeEntityBaseResponse.getData().getHotProductList(), true);
                    }
                });
    }

    public void searchSku(String productUuid) {
        showLoadingDialog();
        ShopUserServiceFactory.shopDetail(productUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<ProductEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<ProductEntity> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        ProductEntity entity = productEntityBaseResponse.getData();
                        if (entity.getItems() == null || entity.getItems().isEmpty()) {
                            addShopCar("-1", 1);
                            return;
                        }
                        if (entity.getItems().size() == 1) {
                            addShopCar(entity.getItems().get(0).getUuid(), 1);
                            return;
                        }
                        new AddShopCarPop(PayResultActivity.this).setShop(productEntityBaseResponse.getData()).setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                            @Override
                            public void doAdd(int num, String itemUuid, String desc) {
                                if (android.text.TextUtils.isEmpty(itemUuid)) {
                                    ToastUtils.showShort("没有库存!");
                                    return;
                                }
                                addShopCar(itemUuid, num);
                            }

                            @Override
                            public void doBuy(int num, String itemUuid, String itemDesc) {

                            }
                        }).showPopupWindow(0, 2000);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    public void addShopCar(String productUuid, int count) {
        showLoadingDialog();
        AddShopCarReq req = new AddShopCarReq();
        req.setItemUuid(productUuid);
        req.setItemCount(count + "");
        ShopUserServiceFactory.addShopCar(req)
                .subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
                    @Override
                    public void onNext(BaseResponse<Object> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("加入购物车成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_handle_1:
                if(StringUtil.isEmpty(type)) {
                    if (payResultHandle1.getText().toString().equals("返回首页")) {
                        ActivityUtils.finishAllActivities();
                        ActivityUtils.startActivity(TabMainActivity.class);
                    } else if (payResultHandle1.getText().toString().equals("重新付款")) {
                        PayMethodPop payMethodPop = new PayMethodPop(this);
                        payMethodPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                int payMethod = payMethodPop.getPayMethod();
                                if (payMethod == PayConfigs.PAY_METHOD_ALIPAY) {
                                    alipay(payUuid);
                                    return;
                                }
                                if (payMethod == PayConfigs.PAY_METHOD_WECHAT) {
                                    wechatPay(payUuid);
                                }
                            }
                        });
                        payMethodPop.showPopupWindow(findViewById(android.R.id.content));
                    }
                }else{
                    ActivityUtils.finishAllActivities();
                    ActivityUtils.startActivity(TabMainActivity.class);
                }
                break;
            case R.id.tv_handle_2:
                if (StringUtil.isEmpty(type)) {
                    Intent intent = new Intent(this, MyOrderDetailActivity.class);
                    intent.putExtra("orderUuid", payUuid);
                    startActivity(intent);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", productId);
                    ActivityUtils.startActivity(bundle, CommentsListActivity.class);

                }
                break;
        }
    }

    public void wechatPay(String uuid) {
        showLoadingDialog();
        ShopUserServiceFactory.wx(uuid)
                .subscribe(new AbstractSubscriber<BaseResponse<WexinPayResult>>(this) {
                    @Override
                    public void onNext(BaseResponse<WexinPayResult> objectBaseResponse) {
                        dismissLoadingDialog();
                        IWXAPI iwxapi = WXAPIFactory.createWXAPI(FlyApplication.getContext(), objectBaseResponse.getData().getAppid(), true);
                        iwxapi.registerApp(objectBaseResponse.getData().getAppid());
                        SharePreferenceManager.setCachedAppKey(objectBaseResponse.getData().getAppid());
                        PayReq payReq = PayUtils.wechatPay(JSON.toJSONString(objectBaseResponse.getData()));
                        iwxapi.sendReq(payReq);
                    }
                });
    }

    public void alipay(String uuid) {
        showLoadingDialog();
        ShopUserServiceFactory.alipay(uuid)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> createOrderPreviewEntityBaseResponse) {
                        dismissLoadingDialog();
                        Log.d("ConfirmOrderPresenter",JSON.toJSONString(createOrderPreviewEntityBaseResponse));
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean isSuccess = PayUtils.aliPay(ActivityUtils.getTopActivity(),createOrderPreviewEntityBaseResponse.getData());
                                if(isSuccess){
                                    Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                                    jump.putExtra("isPaySuccess", true);
                                    jump.putExtra("orderUuid", uuid);
                                    ActivityUtils.startActivity(jump);
                                    finishActivity();
                                    Log.d("ConfirmOrderPresenter","支付成功");
                                }else {
                                    Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                                    jump.putExtra("isPaySuccess", false);
                                    jump.putExtra("orderUuid", uuid);
                                    ActivityUtils.startActivity(jump);
                                    finishActivity();
                                    Log.d("ConfirmOrderPresenter","支付失败");
                                }
                            }
                        }).start();
                    }
                });
    }

    class PayReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), WxConstants.PAY_SUCCESS)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", true);
                jump.putExtra("orderUuid", payUuid);
                ActivityUtils.startActivity(jump);
                finish();
            } else if (TextUtils.equals(intent.getAction(), PAY_FAILED)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", false);
                jump.putExtra("orderUuid", payUuid);
                ActivityUtils.startActivity(jump);
                finish();
            }
        }
    }
}
